/*
 * File: CheckerboardKarel.java
 * ----------------------------
 * When you finish writing it, the CheckerboardKarel class should draw
 * a checkerboard using beepers, as described in Assignment 1.  You
 * should make sure that your program works for all of the sample
 * worlds supplied in the starter folder.
 */

import stanford.karel.*;

public class CheckerboardKarel extends SuperKarel {
	/* Builds a checkboard using beepers 
	 * Precondition: a blank world of NxM is given
	 * Postcondition: a checkboard is built using beepers
	 */
	public void run(){
		/* always fill the first row */
		fillRow();
		
		/* iterate through available rows filling them */
		while(frontIsClear()){
			/* move Karel to next available row */
			moveToNextRow();
			/* fill the row */
			fillRow();
		}
	}
	
	/*
	 *  Fill a row of beepers 
	 *  Precondition: Karel is positioned at the beginning of a blank row
	 *  Postcondition: A row of checkboard beepers is built and Karel ends facing North
	 */
	private void fillRow(){
		/* always put a beeper first, for strange cases */ 
		putBeeper();
		
		while(frontIsClear()){
			/* move once */
			move();
			
			/* if Karel can still move, move again and place a beeper */
			if (frontIsClear()){
				move();
				putBeeper();
			}
			/* if not, will move to the next row available */
		}
		
		/* ends up facing north, in order to start again */
		faceNorth();
	}
	
	/*
	 *  Makes Karel faces North
	 *  Precondition: Karel is facing East or West
	 *  Postcondition: Karel is facing North
	 */
	private void faceNorth(){
		if (facingEast()){
			turnLeft();
		}
		else{
			turnRight();
		}
	}
	
	/*
	 *  Moves Karel to next available Row
	 *  Precondition: Karel is positioned on a Row.
	 *  Postcondition: Karel is positioned on the next available row facing to clear side. 
	 *                 It will move twice if a beeper has been recently put or once if 
	 *                 there are no beepers present
	 */
	private void moveToNextRow(){
			/* In this case, Karel will move twice since we have just put a beeper */
			if (beepersPresent()){
				move();
				
				faceToClearSide();
				
				move();
			}
			/* in this case Karel will move only once, since there are no beepers */
			else{
				move();
				
				faceToClearSide();
			}
		
	}
	
	/*
	 *  Makes Karel face to the clear part of the row (opposite to the wall)
	 *  Precondition: Karel is facing North
	 *  Postcondition: Karel is facing the clear part of the row
	 */
	private void faceToClearSide(){
		turnLeft();
		
		if(frontIsBlocked()){
			turnAround();
			
			if (frontIsBlocked()){
				faceNorth();
			}
		}
	}
}
